import { IAppOption, IMenuItem } from "../typings"
import { ICartItem, IModalCarts } from "../typings/types/cloud-models"
import { eventBus } from "./utils/util"
const cloudbase = require("@cloudbase/wx-cloud-client-sdk");

// app.ts
App<IAppOption>({
  globalData: {
    tabs: [
      { value: 'home', label: '首页', icon: '/images/home.svg', selectedIcon: '/images/home_selected.svg', url: "/pages/index/index" },
      { value: 'menu', label: '点餐', icon: '/images/menu.svg', selectedIcon: '/images/menu_selected.svg', url: "/pages/menu/menu" },
      { value: 'orders', label: '取餐', icon: '/images/order.svg', selectedIcon: '/images/order_selected.svg', url: "/pages/orders/orders" },
      { value: 'mine', label: '个人中心', icon: '/images/mine.svg', selectedIcon: '/images/mine_selected.svg', url: "/pages/mine/mine" },
    ],
    currentTab: 'home',
    cart: [] as ICartItem[],
    isLogin: false,
    checkoutItems: {} as IMenuItem,
    userInfo: undefined,
    tableNumber: '',
    openid: '',
    currentHour: '',
    counter: 0,
  },
  onLaunch() {
    this.initCloud()
    eventBus.on("getOpenid", this.getOpenid)
    this.getOpenid()
  },
  initCloud() {
    // 初始化云开发环境
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        env: 'cloud1-3gkc3d4e1d2d98e6',
        traceUser: true,
      })
      cloudbase.init(wx.cloud);
    }
  },
  getOpenid() {
    const openid = wx.getStorageSync('openid')
    if (openid) {
      this.globalData.openid = openid
      this.globalData.isLogin = true
      return openid
    } else {
      return wx.cloud.callFunction({
        name: 'login_register',
        data: {}
      }).then(res => {
        const result = res.result as { openid: string }
        if (result.openid) {
          this.globalData.openid = result.openid
          this.globalData.isLogin = true
          wx.setStorageSync('openid', result.openid)
          return result.openid
        }
        return ''
      }).catch(err => {
        console.error('获取openid失败', err)
        return ''
      })
    }
  },
  generateOrderNo(): string {

    const now = new Date();

    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const verify = `${year}${month}${day}${hours}` + this.getHourlyIncrementalId();
    return 'HT' + verify + this.generateLuhnCheckDigit(verify)
  },
  getHourlyIncrementalId(): string {
    const now = new Date();
    const hour = now.getHours().toString().padStart(2, '0');

    // 如果小时变了，重置计数器
    if (this.globalData.currentHour !== hour) {
      this.globalData.currentHour = hour;
      this.globalData.counter = 0;
    }

    // 递增并返回 3 位数字
    this.globalData.counter++;
    if (this.globalData.counter > 999) {
      throw new Error("每小时序号超过 999，请调整位数或逻辑");
    }

    return this.globalData.counter.toString().padStart(3, '0');
  },
  generateLuhnCheckDigit(num: string): number {
    let sum = 0;
    let isEven = false; // 从右往左，第一位是奇数

    for (let i = num.length - 1; i >= 0; i--) {
      let digit = parseInt(num[i], 10);

      if (isEven) {
        digit *= 2;
        if (digit > 9) digit -= 9; // 等价于 digit.toString().split('').reduce((a, b) => a + parseInt(b, 10), 0)
      }

      sum += digit;
      isEven = !isEven;
    }

    return (10 - (sum % 10)) % 10;
  },
})